package com.zhiwang.xiaoqu.widget

import android.app.Application
import android.content.Context
import android.os.Build
import android.os.Looper
import android.util.Log
import android.util.TypedValue
import android.view.Gravity
import android.widget.Toast
import androidx.annotation.StringRes
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.content.ContextCompat
import com.zhiwang.xiaoqu.BuildConfig
import com.zhiwang.xiaoqu.R


/**
 *
 *
 * @author hiray
 */

fun sp2px(context: Context, spValue: Float): Int {
    val fontScale = context.resources.displayMetrics.scaledDensity
    return (spValue * fontScale + 0.5f).toInt()
}

fun dp2px(context: Context, dp: Float): Int {
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.resources.displayMetrics).toInt()
}

object Toasty   {
        private var toast: Toast? = null
        private var mApp: Application? = null
        private var mTextView: AppCompatTextView? = null

        fun init(app: Application) {
            mApp = app
        }

        fun message(msg: String) {
            if (Looper.myLooper() != Looper.getMainLooper()) {
                Log.i("Toasty", "当前不是主线程 ")
                return
            }
            createIfNull()
            mTextView?.text = msg
            toast?.show()
        }

        fun message(@StringRes msgResId: Int) {
            mApp?.apply { message(this.getString(msgResId)) }
        }

        fun debugMessage(msg: String) {
            if (BuildConfig.DEBUG)
                message(msg)
        }

        private fun createIfNull() {
            if (toast == null)
                synchronized(Toasty::class.java) {
                    if (toast == null)
                        toast = Toast(mApp)
                    mTextView = AppCompatTextView(mApp!!)
                    mTextView!!.setBackgroundResource(R.drawable.rice)
                    mTextView!!.setPadding(dp2px(mApp!!, 15f), dp2px(mApp!!, 8f), dp2px(mApp!!, 15f), dp2px(mApp!!, 8f))
                    mTextView!!.setTextColor(ContextCompat.getColor(mApp as Context, R.color.toast_text_color))
                    mTextView!!.gravity = Gravity.CENTER_VERTICAL
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        mTextView!!.elevation = 10f
                        mTextView!!.translationZ = 10f
                    }
                    toast!!.duration = Toast.LENGTH_SHORT
                    toast!!.view = mTextView
                }
        }


    }
